<template>
  <div class="channel-edit">
    <!-- 当前登陆用户已经订阅的频道 -->
    <div class="channel">
      <van-cell title="我的频道" :border="false">
        <van-button plain size="mini" type="danger" @click="EditChannels">{{ Editing?'取消':'编辑' }}</van-button>
      </van-cell>
      <van-grid>
        <van-grid-item v-for="(item,index) in channels" :key="item.id" @click="clickMychannel(index)">
          <span :class="{current:index===active}">{{ item.name }}</span>
          <van-icon v-show="Editing&&index!==0" name="cross" class="btn" @click="clickDelChannel(item,index)" />
        </van-grid-item>
      </van-grid>
    </div>
    <!-- 当前登陆用户没有订阅的频道 -->
    <div class="channel">
      <van-cell title="可选频道" :border="false" />
      <van-grid>
        <van-grid-item v-for="(item) in optionChannels" :key="item.id" @click="clickAddChannel(item)">
          <span>{{ item.name }}</span>
        </van-grid-item>
      </van-grid>
    </div>
  </div>
</template>

<script>
import { mapState, mapActions, mapGetters, mapMutations } from 'vuex'
import { reqAddChannel } from '@/api/channel'
export default {
  name: 'ChannelEdit',
  props: {
    active: {
      type: Number,
      default: 0
    }
  },
  data() {
    return {
      Editing: false
    }
  },
  computed: {
    ...mapState('channels', ['channels', 'AllChannels']),
    ...mapGetters('channels', ['optionChannels'])

  },
  created() {
    this.getAllChannelsList()
  },

  methods: {
    ...mapMutations('channels', ['addChannels', 'delChannels']),
    ...mapActions('channels', ['getAllChannelsList']),
    clickMychannel(index) {
      this.$emit('changeChannel', index)
    },
    EditChannels(index) {
      if (index === 0) return
      this.Editing = !this.Editing
    },
    async  clickAddChannel(channel) {
      this.addChannels(channel)
      this.resetChannel()
    },
    clickDelChannel(channel, index) {
      if (index === this.active) {
        this.$emit('update-active', 0)
      }
      if (this.active > index) {
        this.$emit('update-active', this.active - 1)
      }
      this.delChannels(channel)
      this.resetChannel()
    },
    async resetChannel() {
      const channelList = this.channels.map((item, index) => {
        return {
          id: item.id,
          seq: index
        }
      })
      const res = await reqAddChannel(channelList)
      console.log(res)
    }

  }

}
</script>

<style lang="scss" scoped>
.channel{
  padding:15px;
  font-size:14px;
  ::v-deep .van-button--mini {
    height: 22px;
    min-width: 50px;
  }
  .btn {
    position: absolute;
    top: 5px;
    right: 5px;
    font-size: 14px;
  }
  .current {
  color: #e5615b;
  font-weight: bold;
}
}
</style>
